package com.rt.cms.controller;


import com.rt.cms.common.Constants;
import com.rt.cms.common.annotation.SystemLog;
import com.rt.cms.common.base.Page;
import com.rt.cms.common.base.PageResultSet;
import com.rt.cms.common.base.Result;
import com.rt.cms.common.utils.SendMessageUtil;
import com.rt.cms.controller.base.BaseController;
import com.rt.cms.data.dto.company.ArchivesDto;
import com.rt.cms.data.entity.CompanyInfoBean;
import com.rt.cms.data.entity.TbApprovalRecord;
import com.rt.cms.data.entity.TbCompanyInfo;
import com.rt.cms.data.entity.system.User;
import com.rt.cms.service.ApprovalService;
import com.rt.cms.service.ArchivesService;
import com.rt.cms.service.CompanyInfoService;
import com.rt.cms.service.system.UserService;
import com.rt.cms.shiro.realm.UserRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * 档案库管理
 */

@Controller
@RequestMapping(value = "/archives")

public class ArchivesController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(ArchivesController.class);

    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private ApprovalService approvalService;

    @RequiresRoles(value={"root","admin"},logical= Logical.OR)
    @RequestMapping(method = RequestMethod.GET)
    public String toPage(Model model) {
        return "archives/archivesSys";
    }

    @RequestMapping(value = "archives_user", method = RequestMethod.GET)
    public String archivesUser(Model model) {
        return "archives/archivesUserList";
    }

    /**
     * 档案库展示页面
     *
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping("/list")
    // @RequiresPermissions("user:view")
    public PageResultSet<ArchivesDto> list(Page page, HttpServletRequest request,String comName,String status, String comType,String inputTime) {
        User user = (User) request.getAttribute(Constants.CURRENT_USER);
        String dormant=Constants.unDormancy+","+Constants.WaitDormancy;
        int currentId = user.getId().intValue();
        List<User> userlist = userService.selectAllUserBypId(currentId);
        String ids = String.valueOf(currentId);
        /*for (int i = 0; i < userlist.size(); i++) {
            ids = ids + "," + userlist.get(i).getId();
        }*/
        return archivesService.selectByUseParam(status, page, ids, comName,0,dormant,comType,inputTime);
    }

    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    //@RequiresPermissions("user:create")
    @SystemLog("档案创建")
    public Result create(@Valid TbCompanyInfo tbCompanyInfo) {

        archivesService.create(tbCompanyInfo);
        return Result.Success();
    }

    /**
     * 档案库编辑页面
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    // @RequiresPermissions("user:view")
    @SystemLog("档案库更新")
    public Result update(TbCompanyInfo tbCompanyInfo) {

        archivesService.update(tbCompanyInfo);

        return Result.Success();
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    // @RequiresPermissions("user:delete")
    @SystemLog("档案 休眠用户")
    public Result delete(TbCompanyInfo tbCompanyInfo) {
        archivesService.delete(tbCompanyInfo.getId());
        return Result.Success();
    }

    /**
     * 企业和担保方详情
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/detail")
    // @RequiresPermissions("user:view")
    public String detail(int id, Model model) {

        CompanyInfoBean companyInfoBean = companyInfoService.getCompanyInfoBeanById(id);

        List<CompanyInfoBean> companyInfoBeans = companyInfoService.getGuaranteeCompanyInfoBean(id);

        model.addAttribute("archives", companyInfoBean);

        model.addAttribute("archivesGuarantees", companyInfoBeans);
        Subject subject = SecurityUtils.getSubject();
        if (subject.hasRole("admin")){
            return "archives/archivesDetailSys";
        };
        return "archives/archivesDetail";
    }

    /**
     * 历史记录
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/historyLoad")
    public String historyLoad(int id, Model model) {
        model.addAttribute("id", id);
        return "archives/archivesHistoryRecord";
    }

    @RequestMapping("/history")
    @ResponseBody
    public PageResultSet<TbApprovalRecord> history(Page page,String id) {
        return approvalService.queryHistoryRecord(Integer.parseInt(id),page);
    }


    /**
     * 档案审核操作
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkStatus", method = RequestMethod.POST)
    // @RequiresPermissions("user:view")
    public Result queryByStatusDepartCheck(TbCompanyInfo tbCompanyInfo, HttpServletRequest request) {
        //更新状态
        int operateType = tbCompanyInfo.getOperateType();
        //记录操作记录
        User user = (User) request.getAttribute(Constants.CURRENT_USER);
        Date now = new Date();
        tbCompanyInfo.setInputTime(now);
        TbApprovalRecord tbApprovalRecord = new TbApprovalRecord();
        tbApprovalRecord.setOperateId(user.getId().intValue());
        tbApprovalRecord.setOperateTime(now);
        tbApprovalRecord.setDemo(tbCompanyInfo.getRemark());
        if (Constants.InFile == Integer.valueOf(operateType)) {
            tbCompanyInfo.setStatus(Constants.On_File);
            tbApprovalRecord.setOperateType(Constants.InFile);
            tbApprovalRecord.setStatus(Constants.On_File);
        } else if(Constants.OutFile==Integer.valueOf(operateType)){
            tbCompanyInfo.setStatus(Constants.Due_Diligence);
            tbApprovalRecord.setOperateType(Constants.OutFile);
            tbApprovalRecord.setStatus(Constants.Due_Diligence);
        }else if (Constants.InDormancy==Integer.valueOf(operateType)){
            //申请休眠
            tbCompanyInfo.setDormant(Constants.WaitDormancy);
            tbApprovalRecord.setOperateType(Constants.InDormancy);
            tbApprovalRecord.setStatus(Constants.WaitDormancy);


            // 给B发短信
            // 此时可能B角从未操作过，因此不能在tb_company_info中取，只能在sys_user中取pid
            String phone = userService.queryParentPhoneById(companyInfoService.getCompanyInfoById(tbCompanyInfo.getId()).getOperateId());
            SendMessageUtil.postUrl(Constants.Sms_InDormancy, Constants.Sms_URL, phone);

        }
        //修改企业信息
        if (companyInfoService.editCompanyInfo(tbCompanyInfo, tbApprovalRecord) > 0) {
            //map.put("message", "修改企业信息成功");
        } else {
            //map.put("message", "修改企业信息失败");
        }
        return Result.Success();
    }


    /**
     * 档案库根据操作人id展示页面
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByOperateID")
    // @RequiresPermissions("user:view")
    public PageResultSet<ArchivesDto> findByOperateID(Page page, Integer id) {

        return archivesService.findByOperateID(page, id);
    }

    /**
     * 用于跳转操作人档案库页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/findByOperateIDView")
    // @RequiresPermissions("user:view")
    public String findByOperateIDView(int id, Model model) {
        model.addAttribute("operateID", id);
        return "archives/archivesList";
    }

    @ResponseBody
    @RequestMapping("/test")
    // @RequiresPermissions("user:view")
    public Result list(Model model) {
        model.addAttribute("name", "name");
        // return "company/blank";
        return Result.Success();
    }

    @RequestMapping("/approvalRecordList")
    @ResponseBody
    public Map<String,Object> approvalRecordList(int id, Model model) {

        Map<String,Object> map = new HashedMap();
        List<TbApprovalRecord> list = approvalService.queryApprovalRecordByUsrId(id);
        map.put("status",0);
        map.put("msglist",list);

        return map;
    }

    @RequestMapping("/dormanyRecordList")
    @ResponseBody
    public Map<String,Object> dormanyRecordList(int id, Model model) {

        Map<String,Object> map = new HashedMap();
        List<TbApprovalRecord> list = approvalService.queryDormanyRecordByUsrId(id);
        map.put("status",0);
        map.put("msglist",list);

        return map;
    }

    @RequestMapping("/waitDormanyRecordList")
    @ResponseBody
    public Map<String,Object> waitDormanyRecordList(int id, Model model) {

        Map<String,Object> map = new HashedMap();
        List<TbApprovalRecord> list = approvalService.queryWaitDormanyRecordByUsrId(id);
        map.put("status",0);
        map.put("msglist",list);

        return map;
    }
}

